﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace EmailDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Title = "Home Page";

            return View();
        }
        private string sFrom = "techcenter@siluguanghui.com"; //邮箱
        private string spass = "Jiuzhizun@%*0801"; //此处为邮箱开启smtp服务获取到的密码

        public async Task<ActionResult> SendEmail()
        {
            MailMessage msg = new MailMessage();
            msg.To.Add("729628777@qq.com");
            //msg.To.Add(b@b.com);
            /*  
             msg.To.Add("b@b.com");  
            * msg.To.Add("b@b.com");  
            * msg.To.Add("b@b.com");可以发送给多人  
            */
            //msg.CC.Add(c@c.com);
            /*  
            * msg.CC.Add("c@c.com");  
            * msg.CC.Add("c@c.com");可以抄送给多人  
            */
            msg.From = new MailAddress("techcenter@siluguanghui.com", "丝路广惠", System.Text.Encoding.UTF8);
            /* 上面3个参数分别是发件人地址（可以随便写），发件人姓名，编码*/
            msg.Subject = "这是测试邮件";//邮件标题   
            msg.SubjectEncoding = System.Text.Encoding.UTF8;//邮件标题编码   
            msg.Body = "邮件内容";//邮件内容   
            msg.BodyEncoding = System.Text.Encoding.UTF8;//邮件内容编码   
            msg.IsBodyHtml = false;//是否是HTML邮件   
            msg.Priority = MailPriority.High;//邮件优先级   
            //上述写你的GMail邮箱和密码   

            string strSC = "smtp." + sFrom.Substring(sFrom.IndexOf("@") + 1);

            SmtpClient client = new SmtpClient(strSC);
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential(sFrom, spass);
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.EnableSsl = false;//经过ssl加密   

            object userState = msg;
            try
            {
                //client.SendAsync(msg, userState);
                client.Send(msg);
                return View();
            }
            catch (SmtpException ex)
            {
                return View();
            }
        }
    }
}
